package com.itcast.zuul.Controller;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class LoginFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        //顺序设置
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        //返回true表示过滤器生效
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //登录校验逻辑
        //1获取zuul提供的请求上下文
        RequestContext ctx=RequestContext.getCurrentContext();
        //2从上下文获取request对象
        HttpServletRequest req=ctx.getRequest();
        //3从上下文获取toke
        String token=req.getParameter("access-toke");
        //4判断
        if(token==null||"".equals(token.trim())){
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());
        }
        return null;
    }
}
